<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    {{dataForm}}
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
    <el-form-item label="模板名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="模板名称"></el-input>
    </el-form-item>
    <el-form-item label="关联规格" prop="specIds">
      <!--如果 Select 的绑定值为对象类型，请务必指定 value-key 作为它的唯一性标识。-->
      <el-select v-model="dataForm.specIds" value-key="id" multiple placeholder="请选择">
        <el-option
          v-for="item in specIds"
          :key="item.id"
          :label="item.text"
          :value="item">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="关联品牌" prop="brandIds">
      <!--如果 Select 的绑定值为对象类型，请务必指定 value-key 作为它的唯一性标识。-->
      <el-select v-model="dataForm.brandIds" value-key="id" multiple placeholder="请选择">
        <el-option
          v-for="item in brands"
          :key="item.id"
          :label="item.text"
          :value="item">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="自定义属性">
      <!--<el-input v-model="dataForm.customAttributeItems" placeholder="自定义属性"></el-input>-->
      <el-button type="primary"  @click="dataForm.customAttributeItems.push({})">自定义扩展属性</el-button>
      <el-table
        :data="dataForm.customAttributeItems"
        style="width: 100%">
        <el-table-column
          type="selection"
          align="center"
          width="55">
        </el-table-column>
        <el-table-column
          label="属性名称"
          align="center"
          width="300">
          <template slot-scope="scope">
            <el-input v-model="scope.row.text" placeholder="属性名称" size="small"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180">
          <template slot-scope="scope">
            <el-button @click="dataForm.customAttributeItems.splice(scope.$index,1)" size="small" plain type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        brands:[],
        specIds:[],
        dataForm: {
          id: 0,
          name: '',
          specIds: [],
          brandIds: [],
          customAttributeItems: []
        },
        dataRule: {
          name: [
            { required: true, message: '模板名称不能为空', trigger: 'blur' }
          ],
          specIds: [
            { required: true, message: '关联规格不能为空', trigger: 'blur' }
          ],
          brandIds: [
            { required: true, message: '关联品牌不能为空', trigger: 'blur' }
          ],
          customAttributeItems: [
            { required: true, message: '自定义属性不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.findBrands();
      this.findSpecIds();
    },
    methods: {
      findBrands(){
        this.$http({
          url: this.$http.adornUrl(`/manager/brand/findAll`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("template-data:",data);
            //处理数据为{'id':1,'text':'hello'}
            this.brands = data.list.map(m=> {
              return {'id':m['id'],'text':m['name']};
            })
          }
        })
      },
      findSpecIds(){
        this.$http({
          url: this.$http.adornUrl(`/manager/specification/findAll`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("specification-data:",data);
            //处理数据为{'id':1,'text':'hello'}
            this.specIds = data.list.map(m=>{
              return {'id':m['id'],'text':m['specName']}
            });
          }
        })
      },
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {   //如果是修改操作，就从数据库中根据模板id查询出此模板
            this.$http({
              url: this.$http.adornUrl(`/manager/typetemplate/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.typeTemplate.name
                this.dataForm.specIds = this.converToStr(data.typeTemplate.specIds,'text');
                //console.log("specIds:",data.typeTemplate.specIds)
                // this.dataForm.brandIds = JSON.parse(data.typeTemplate.brandIds).map(m=>{
                //   return {'id':m['id']+"",'text':m['text']}
                // });
                this.dataForm.brandIds = this.converToStr(data.typeTemplate.brandIds,'text');
                this.dataForm.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems);
              }
            })
          }
        })
      },
      converToStr(str,key){
        //1. 转换字符串为对象
        let obj = JSON.parse(str);
        //2. 再处理其中的id为字符串类型,否则，不会自动选中
        return obj.map(m=>{
          return {"id":m.id+"","text":m[key]};
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/manager/typetemplate/${!this.dataForm.id ? 'save' : 'update'}`),
              method: `${this.dataForm.id?'put':'post'}`,
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'specIds': JSON.stringify(this.dataForm.specIds),
                'brandIds': JSON.stringify(this.dataForm.brandIds),
                'customAttributeItems': JSON.stringify(this.dataForm.customAttributeItems)
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
